package com.example.chatchatbackend.handler;

import com.example.chatchatbackend.entity.dto.Message;
import com.example.chatchatbackend.entity.vo.response.MessageVO;
import com.example.chatchatbackend.entity.vo.response.SensitivewordsVO;
import com.example.chatchatbackend.service.MessageService;
import com.example.chatchatbackend.service.SensitivewordsService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WordsHandler {

    @Resource
    MessageService messageService;
    @Resource
    SensitivewordsService sensitivewordsService;

    @XxlJob("WordsHandler")
    public void execute(){
        XxlJobHelper.log("Xxl-Job:Insert");
        List<Message> messages = messageService.findNewMessage();
        log.info("所需发送消息：{}",messages);
        if(messages.isEmpty()){
            XxlJobHelper.log("无检测到所需回复新消息");
            return;
        }
        List<Integer> messageId = messages.stream()
                .map(Message::getId)
                .limit(1)
                .collect(Collectors.toList());

        SensitivewordsVO sensitiveword  = sensitivewordsService.checkMessagesAndRespond(messageId);

        List<MessageVO> messageVOList = messageService.findByIds(messageId);


        MessageVO messageVO = new MessageVO(null,messageVOList.get(0).getToId(),messageVOList.get(0).getSendId(),sensitiveword.getWord());

        messageVOList.get(0).setIsRespond(1);
        messageService.updateMessage(messageVOList.get(0));

        messageVO.setIsRespond(1);
        messageVO.setIsRobot(1);
        log.info("插入到数据库:{}",messageVO);
        messageService.insertMessage(messageVO);

//        messageService.saveMessageById(messageVOList.get(0).getToId(),messageVOList.get(0).getSendId(),sensitiveword.getWord());

        }

}
